import {
  Button,
  Carousel,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  RadioButton,
  RadioGroup,
  Space,
  Table,
  Textarea,
  Upload
} from 'ant-design-vue'
import row from 'ant-design-vue/lib/row'
import moment from 'moment'
import { done } from 'nprogress'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { commonApi, riverApi } from '@/apis'
import { BannerItem } from '@/apis/cinemaTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import UploadFile from '@/components/UploadFile'
import { FILE_TYPE } from '@/components/UploadFile/types'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks/useDialog'
import { bus, optionsToMap } from '@/utils'

import { forceOptions } from '../financeManage/constants'
import { getRejectTypeStr } from './common'

export default defineComponent({
  name: 'RvSupplierManage',
  setup() {
    const { showConfirm } = useDialog()
    const StatusOptions = [
      { label: '公户账户', value: 1 },
      { label: '法人账户', value: 2 }
    ]
    const tableRef = ref({} as ProTableRef)
    const showDialog = ref(false)
    const showDialog1 = ref(false)
    const showDialog2 = ref(false)
    const dialogLoading = ref(false)

    const uploadUrl = ref('')
    const editedContent = ref('')
    const uploadOptionItem = ref({})

    const oneRow = ref({})

    const fileList = ref([])
    const statusCur = ref(-1)
    const rejectDlgRef = ref({})
    const awaitCount = ref(0)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '公司名称',
              field: 'corporateName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入公司名称',
                  allowClear: true
                }
              }
            },
            {
              title: '法人代表',
              field: 'legalPerson',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入法人代表',
                  allowClear: true
                }
              }
            },
            {
              title: '联系人电话',
              field: 'applicantMobile',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入联系人电话',
                  allowClear: true
                }
              }
            },
            {
              title: '提交申请时间',
              field: 'timeRange',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['subjectTimeBegin', 'subjectTimeEnd']
                }
              }
            },
            {
              title: '是否上传合同',
              field: 'isUpload',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                options: forceOptions,
                props: {
                  placeholder: '全部',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 150,
          resizable: true
        },
        columns: [
          {
            title: '公司名称',
            field: 'corporateName',
            width: 180
          },
          {
            title: '统一社会信用代码',
            field: 'licenseNumber',
            width: 160
          },
          {
            title: '服务商法人姓名',
            field: 'legalPerson',
            width: 80
          },
          {
            title: '服务商银行开户支行',
            field: 'bankName'
          },
          {
            title: '服务商银行账号',
            field: 'accountNumber',
            width: 170
          },
          {
            title: '总裁法人姓名',
            field: 'presidentBankLegalPerson'
          },
          {
            title: '总裁银行开户支行',
            field: 'presidentBankName'
          },
          {
            title: '总裁银行账号',
            field: 'presidentAccountNumber'
          },
          {
            title: '账号状态',
            field: 'bankAccountType',
            formatter: ({ cellValue }) => {
              return optionsToMap(StatusOptions)[cellValue]
            }
          },
          {
            title: '申请人联系电话',
            field: 'applicantMobile'
          },
          {
            title: '身份证号',
            field: 'idCardNumber'
          },
          {
            title: '是否上传合同',
            field: 'isUpload',
            formatter: ({ cellValue }) => {
              return optionsToMap(forceOptions)[cellValue]
            }
          },
          {
            title: '提交申请时间',
            field: 'subjectTime',
            width: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '服务商审核状态',
            field: 'auditStatusName',
            width: 120
          },
          {
            title: '总裁审核状态',
            field: 'presidentAuditStatusName',
            width: 100
          },
          {
            title: '审核通过时间',
            field: 'auditTime',
            width: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '最新驳回时间',
            field: 'rejectTime',
            width: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '操作',
            width: 170,
            fixed: 'right',
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await riverApi.getSupplierList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form,
                auditStatus: statusCur.value != -1 ? statusCur.value : null
              })
              getWaitCount(form)
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshSupplierList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    //获取待审核
    async function getWaitCount(form) {
      try {
        const data = await riverApi.getSupplierList({
          pageParameter: {
            pageSize: 15,
            currentPage: 1
          },
          auditStatus: 0,
          ...form
        })
        awaitCount.value = data.page.totalCount
      } finally {
      }
    }

    const router = useRouter()

    //查看详情
    function handleDetail(item) {
      router.push({
        name: 'RvSupplierDetail',
        query: {
          id: item.id,
          type: 'preview'
        }
      })
    }

    function handleEditDetail(item) {
      router.push({
        name: 'EditRvSupplierDetail',
        query: {
          id: item.id
        }
      })
    }

    //服务商审核
    function handleVerify(item) {
      router.push({
        name: 'RvSupplierDetail',
        query: {
          id: item.id,
          flag: 1
        }
      })
    }
    //总裁审核
    function presidentHandleVerify(item) {
      router.push({
        name: 'RvSupplierDetail',
        query: {
          id: item.id,
          flag: 2
        }
      })
    }

    //驳回理由
    function handleRejectReason(item) {
      showConfirm({
        content: `${item.auditDetail}${getRejectTypeStr(item.auditDetailType)}`
      })
    }

    //上传合同
    function handleUploadContract(item) {
      showDialog2.value = true
      oneRow.value = { ...item }
      if (item.contractUrl) {
        uploadUrl.value = item.contractUrl
      } else {
        uploadUrl.value = ''
      }
    }

    // 点击上传
    async function uploadPdf(item) {
      if (!uploadUrl.value) {
        message.error('请上传合同')
        return
      }
      try {
        const contractUrl = uploadUrl.value
        const id = oneRow.value.id
        await riverApi.uploadContract({ contractUrl, id })
      } finally {
        showDialog2.value = false
        refresh()
        message.success('上传成功')
      }
    }

    function previewFile(file: any) {
      // console.log('Your upload file:', File)
      // return fetch('', {
      //   method: 'POST',
      //   body: file
      // })
      //   .then(res => res.json())
      //   .then(({ thumbnail }) => thumbnail)
    }

    async function handleUploadReject() {
      // try {
      //   await riverApi.rejectReview({
      //     id: modalId.value,
      //     auditDetail: modalText.value
      //   })
      // } finally {
      //   showDialog2.value = false
      //   modalId.value = 0
      //   modalText.value = ''
      //   refresh()
      // }
    }

    //刷新
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }

    //备注
    function handleRemark(item) {}

    //历史记录
    function handleHistory(item) {}

    //驳回
    const modalId = ref(0)
    const modalText = ref('')
    function handleCancelReject() {
      modalId.value = 0
      modalText.value = ''
    }
    function handleRejectModal(item) {
      modalId.value = item.id
      showDialog.value = true
    }
    function handlePresidentRejectModal(item) {
      modalId.value = item.id
      showDialog1.value = true
    }
    async function handleReject() {
      try {
        await riverApi.rejectReview({
          id: modalId.value,
          auditDetail: modalText.value
        })
      } finally {
        showDialog.value = false
        modalId.value = 0
        modalText.value = ''
        refresh()
      }
    }
    async function handlePresidentReject() {
      try {
        await riverApi.presidentRejectReview({
          id: modalId.value,
          auditDetail: modalText.value
        })
      } finally {
        showDialog1.value = false
        modalId.value = 0
        modalText.value = ''
        refresh()
      }
    }
    // 操作记录
    function checkaAtion(item) {
      router.push({
        name: 'RvSupplierManageRecord',
        query: {
          id: item.id
        }
      })
    }
    return {
      statusCur,
      tableRef,
      dialogLoading,
      tableConfig,
      showDialog,
      showDialog1,
      showDialog2,
      rejectDlgRef,
      awaitCount,
      modalText,
      modalId,
      fileList,
      uploadUrl,
      uploadOptionItem,
      // uploadlist,
      checkaAtion,
      handleDetail,
      handleEditDetail,
      handleVerify,
      presidentHandleVerify,
      handleRemark,
      handleHistory,
      handleReject,
      handleUploadReject,
      handleCancelReject,
      uploadPdf,
      refresh,
      handleRejectModal,
      handlePresidentRejectModal,
      handleRejectReason,
      handlePresidentReject,
      handleUploadContract,
      previewFile
      // handlePreview,
      // handleUploadChange
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => {
              return (
                <RadioGroup
                  v-model:value={this.statusCur}
                  onChange={() => {
                    this.tableRef.refresh()
                  }}
                >
                  <RadioButton value={-1}>全部</RadioButton>
                  <RadioButton value={0}>{`待审核${
                    this.awaitCount ? '(' + this.awaitCount + ')' : ''
                  }`}</RadioButton>
                  <RadioButton value={1}>审核通过</RadioButton>
                  <RadioButton value={2}>驳回申请</RadioButton>
                </RadioGroup>
              )
            },
            operation: ({ row }) => (
              <div>
                <Button
                  type="link"
                  size="small"
                  v-show={
                    row.auditStatus == 1 ||
                    row.auditStatus == 2 ||
                    row.presidentAuditStatus == 1 ||
                    row.presidentAuditStatus == 2
                  }
                  onClick={() => this.handleDetail(row)}
                >
                  查看详情
                </Button>
                <Button
                  v-show={row.auditStatus == 0}
                  type="link"
                  size="small"
                  onClick={() => this.handleVerify(row)}
                >
                  服务商审核
                </Button>
                <Button
                  v-show={row.presidentAuditStatus == 0}
                  type="link"
                  size="small"
                  onClick={() => this.presidentHandleVerify(row)}
                >
                  总裁审核
                </Button>
                {/* <Button type="link"
                  size="small"onClick={() => this.handleRemark(row)}>
                  备注
                </Button>
                <Button type="link"   size="small" onClick={() => this.handleHistory(row)}>
                  历史记录
                </Button> */}
                <Button
                  type="link"
                  size="small"
                  v-show={row.auditStatus == 2 || row.presidentAuditStatus == 2}
                  onClick={() => this.handleRejectReason(row)}
                >
                  驳回理由
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleUploadContract(row)}
                >
                  {row.contractUrl ? '编辑合同' : '上传合同'}
                </Button>
                <Button
                  type="link"
                  size="small"
                  v-show={row.auditStatus == 1}
                  onClick={() => this.handleRejectModal(row)}
                >
                  服务商驳回
                </Button>
                <Button
                  type="link"
                  size="small"
                  v-show={row.presidentAuditStatus == 1}
                  onClick={() => this.handlePresidentRejectModal(row)}
                >
                  总裁驳回
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEditDetail(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.checkaAtion(row)}
                >
                  操作日志
                </Button>
              </div>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showDialog}
          confirmLoading={this.dialogLoading}
          width={500}
          title={'驳回'}
          onOk={this.handleReject}
          onCancel={this.handleCancelReject}
        >
          <div>驳回原因</div>
          <Textarea
            placeholder="请输入"
            style={{
              height: '100px',
              width: '400px',
              marginTop: '20px',
              marginLeft: '20px',
              marginBottom: '20px'
            }}
            v-model:value={this.modalText}
          ></Textarea>
        </Modal>
        <Modal
          v-model:visible={this.showDialog1}
          confirmLoading={this.dialogLoading}
          width={500}
          title={'驳回'}
          onOk={this.handlePresidentReject}
          onCancel={this.handleCancelReject}
        >
          <div>驳回原因</div>
          <Textarea
            placeholder="请输入"
            style={{
              height: '100px',
              width: '400px',
              marginTop: '20px',
              marginLeft: '20px',
              marginBottom: '20px'
            }}
            v-model:value={this.modalText}
          ></Textarea>
        </Modal>
        <Modal
          v-model:visible={this.showDialog2}
          confirmLoading={this.dialogLoading}
          onOk={this.uploadPdf}
          width={500}
          title={this.uploadUrl ? '编辑合同' : '上传合同'}
          style={{
            textAlign: 'center'
          }}
          destroyOnClose
        >
          <Form labelCol={{ span: 5 }} style={{ marginTop: '15px' }} required>
            <FormItem label="上传合同" required>
              <UploadFile
                v-model={[this.uploadUrl, 'urls']}
                maxLength={1}
                fileType={'pdf'}
              >
                <Button>上传合同</Button>
              </UploadFile>
            </FormItem>
          </Form>
          <span>仅支持pdf文件上传，最多上传1个文件</span>
        </Modal>
      </div>
    )
  }
})
